package com.threez.common.dubbo.domain;

import com.threez.core.constant.Constants;
import com.threez.core.domain.R;
import com.threez.core.exception.enums.BaseExceptionEnums;
import com.threez.core.exception.enums.GlobalExceptionEnum;
import com.threez.core.utils.StringUtils;
import lombok.Data;

import java.io.Serializable;
import java.util.Optional;

/**
 * dubbo响应
 * @author zhaozz
 * @title DubboResp
 * @date 2023/1/14 14:14
 */
@Data
public class DubboResp<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 成功
     */
    public static final String SUCCESS = Constants.SUCCESS;

    /**
     * 失败
     */
    public static final String FAIL = String.join("_", GlobalExceptionEnum.GLOBAL_ERROR.getModuleName(), GlobalExceptionEnum.GLOBAL_ERROR.getCode());

    /**
     * 消息状态码
     */
    private String code;

    /**
     * 消息内容
     */
    private String msg;

    /**
     * 数据对象
     */
    private T data;

    public Boolean isSuccess() {
        return R.SUCCESS.equals(getCode());
    }
    public static <T> DubboResp<T> ok( T data) {
        return restResult(SUCCESS, "操作成功", data);
    }
    public static <T> DubboResp<T> ok( ) {
        return restResult(SUCCESS, "操作成功", null);
    }
    public static <T> DubboResp<T> fail(String code, String msg, T data) {
        return restResult(code, msg, data);
    }
    public static <T> DubboResp<T> fail(String code, String msg) {
        return restResult(code, msg, null);
    }
    public static <T> DubboResp<T> fail(BaseExceptionEnums baseExceptionEnums , String... msg) {
        String code = String.join("_", baseExceptionEnums.getModuleName(), baseExceptionEnums.getCode());
        String des = Optional.ofNullable(msg)
                .map(item -> StringUtils.format(baseExceptionEnums.getMsg(), item))
                .orElseGet(() -> baseExceptionEnums.getMsg());
        return restResult(code, des, null);
    }

    private static <T> DubboResp<T> restResult(String code, String msg, T data) {
        DubboResp<T> dubboResp = new DubboResp<>();
        dubboResp.setCode(code);
        dubboResp.setData(data);
        dubboResp.setMsg(msg);
        return dubboResp;
    }

}

